﻿using System;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace Browser
{
    public partial class Mainform : Form
    {
        private string _currentUserId;
        public Mainform()
        {
            InitializeComponent();

            _currentUserId = Login(CheckLogin);
            if (string.IsNullOrEmpty(_currentUserId))
            {
                Environment.Exit(0);
            }
        }

        private void Mainform_Load(object sender, EventArgs e)
        {
            try
            {
                Text = ParametersManager.Name;
                label1.Text = $@"正在加载{ParametersManager.Name}数据";
                NavToIndex(_currentUserId);
            }
            catch (System.Net.WebException ex)
            {
                LogHelper.WriteLog(ex);
                MyMessageBox.ShowErrorMsg("网站无法访问，请联系系统管理员");
                Close();
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                MyMessageBox.ShowErrorMsg(ex.Message);
                Close();
            }
        }

        private string Login(Func<string,string,string > checkUserFunc)
        {
            var loginFrm = new Login(checkUserFunc);
            return loginFrm.ShowDialog() != DialogResult.OK ? string.Empty : loginFrm.UserID;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns>验证失败返回string.Empty，验证成功返回userid的值</returns>
        private string CheckLogin(string userName, string password)
        {
            var url = @"http://121.22.5.39/api/User/BindMachine";
            var bandingReturnJson = new HttpRequest().HttpGet(url, $"loginname={userName}&password={password}");
            return Regex.Match(bandingReturnJson, @"UserID\\"":\\""(.*?)\\""").Groups[1].Value; 
        }

        private void NavToIndex(string userId)
        {
            var url = "http://121.22.5.39/UserLoginByApi.aspx";

            var currentDate = DateTime.Now.Date.ToString("yyyy-MM-dd");
            var currentHour = DateTime.Now.Hour;
            var returnString = $"{url}?user={userId}&value={MD5.GetMD5(MD5.GetMD5(userId+ currentDate + currentHour))}";
            LogHelper.WriteLog("开始加载页面");
            webView2.Url = returnString;
        }

        private void webView2_NewWindow(object sender, EO.WebBrowser.NewWindowEventArgs e)
        {
            //此处处理用户打开新窗口行为，目前禁止用户打开新窗口，仅记录日志
            if (string.Equals(e.TargetUrl, "http://121.22.5.39/index.aspx", StringComparison.OrdinalIgnoreCase))
            {
                System.Diagnostics.Process.Start(e.TargetUrl);
            }
            else
            {
                LogHelper.WriteLog($"尝试打开：{e.TargetUrl}被阻止");
            }
            
        }

        private void webView2_BeforeContextMenu(object sender, EO.WebBrowser.BeforeContextMenuEventArgs e)
        {
            //屏蔽网页右键菜单
            e.Menu.Items.Clear();
        }

        private void webView2_LoadCompleted(object sender, EO.WebBrowser.LoadCompletedEventArgs e)
        {
            LogHelper.WriteLog("完成加载页面");
            SuspendLayout();
            webControl1.BringToFront();
            panel1.Visible = false;
            ResumeLayout();
        }

        private void Mainform_Resize(object sender, EventArgs e)
        {
            panel2.Location = new System.Drawing.Point((panel1.Width - panel2.Width) / 2, (panel1.Height - panel2.Height) / 2);
        }

        private void webView2_LoadFailed(object sender, EO.WebBrowser.LoadFailedEventArgs e)
        {
            LogHelper.WriteLog($"加载页面失败:{e.ErrorMessage}");
            SuspendLayout();
            webControl1.BringToFront();
            panel1.Visible = false;
            ResumeLayout();
            MyMessageBox.ShowErrorMsg("打开主页面超时，请联系系统管理员");
        }
    }
}
